package cn.itcast.up.common2

import java.io.{File, FileOutputStream}
import java.util.Properties

import cn.itcast.up.common.HDFSUtils
import org.apache.oozie.client.OozieClient


object MyOozieUtils {
  //获取一个类加载器
  private val loader: ClassLoader = getClass.getClassLoader

  def start(props: Properties) = {
    //构建Oozie调度的相关配置
    //1.先获取oozie启动的相关配置job.properties
    //获取up.conf中的oozie配置,赋值给props
    val params: Map[String, String] = UpHolder.oozie.params
    for ((k, v) <- params) {
      props.setProperty(k, v)
    }

    //获取当前模型的ID
    val modelID: String = props.getProperty("modelID")
    val appPath = "/apps/tags_new/models/tags_" + modelID
    //TODO  懒汉模式再了解一手,创建应用的目录
    HDFSUtils.getInstance().mkdir(appPath)
    //补充配置文件中确实的信息:start/end/mainclass/path
    props.setProperty("appPath", "hdfs://node01:9000/apps/tags_new/models/tags_" + modelID)
    props.setProperty(OozieClient.COORDINATOR_APP_PATH, "hdfs://node01:9000/apps/tags_new/models/tags_" + modelID)

    //2. 将workflow.xml, coordinater.xml, job.properties上传到HDFS的指定目录下.

    //使用类的加载器来获取资源文件
    val workflowPath: String = loader.getResource("oozie/workflow.xml").getPath
    val coordinatorPath: String = loader.getResource("oozie/coordinator.xml").getPath
    val propertiesPath: String = loader.getResource("oozie/job.properties").getPath
    HDFSUtils.getInstance().copyFromFile(workflowPath, appPath + "/workflow.xml")
    HDFSUtils.getInstance().copyFromFile(coordinatorPath, appPath + "/coordinator.xml")
    //将props配置保存到本地
    props.store(new FileOutputStream(new File(propertiesPath)),"hehe")
    HDFSUtils.getInstance().copyFromFile(propertiesPath, appPath + "/job.properties")

    //启动Oozie,指定启动配置文件job.properties
    val client: OozieClient = new OozieClient(UpHolder.oozie.url)
    //启动/停止
    val jobId: String = client.run(props)
    println(jobId)
    //停止作业0000007-191231142426171-oozie-root-C
    //    client.kill(jobId)
  }

  def main(args: Array[String]): Unit = {
    val props = new Properties()
    props.setProperty("start","2019-09-24T06:15+0800")
    props.setProperty("end", "2030-09-24T06:15+0800")
    props.setProperty("mainClass", "cn.itcast.up29.TestTag")
    props.setProperty("jarPath", "hdfs://node01:9000/apps/tags_new/models/tags_99/model29.jar")
    props.setProperty("modelID", "99")
    //start(props)
    println(props.toString)
  }

}
